package org.feng.navigation.web.config;

import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * LocalDateTime 序列化&反序列化配置
 *
 * @version V1.0
 * @author: junzi
 * @date: 2023年01月13日 15时54分
 */
@Configuration
public class LocalDateTimeSerializerConfig {
    /**
     * 时间格式<br>
     * 也可以在配置中修改：
     * <pre>
     *     spring:
     * 	        jackson:
     * 		        date-format: yyyy-MM-dd HH:mm:ss
     * 		        time-zone: GMT+8
     * </pre>
     */
    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;

    /**
     * 序列化 LocalDateTime
     *
     * @return LocalDateTime 序列化实例
     */
    public LocalDateTimeSerializer localDateTimeSerializer() {
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
    }

    /**
     * 反序列化 LocalDateTime
     *
     * @return LocalDateTime 反序列化实例
     */
    public LocalDateTimeDeserializer localDateTimeDeserializer() {
        return new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(pattern));
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder
                .serializerByType(LocalDateTime.class, localDateTimeSerializer())
                .deserializerByType(LocalDateTime.class, localDateTimeDeserializer());
    }
}
